package util.toolkit;

import java.sql.Timestamp;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
/*
 * 该类用于应用系统中，日期和字符串类型的常用转换操作
 * 作者：张锦盛
 */
public class HtmlStrUtil {

	/*
	 * 将一个完整日期字符串截取为只有年月日小时分的字符串
	 * 输入parseToDatetime("1978-6-2 8:26:44.903");
	 * 截取后返回得到"1978-6-2 8:26"
	*/
	public static String parseToDatetime(String date){
		if(date!=null || !date.equals("")){
			if(date.length()>10 ||date.indexOf(":")>0){ 
				int lastIndex = date.lastIndexOf(":"); 
				return date.substring(0, lastIndex);
			}
			else{
				return date;
			}
		}else{
			return date;
		}
	}
	
	/*
	 * 将一个完整日期字符串截取为只有年月日的字符串
	 * 输入parseDate("1978-6-2 8:26:44.903");
	 * 截取后返回得到"1978-6-2"
	 */
	public static String parseDate(String date){
		if(date!=null){
			if(date.length()>10 ||date.indexOf(":")>0){
				int lastIndex = date.lastIndexOf(" "); 
				return date.substring(0, lastIndex);
			}
			else{
				return date;
			}
		}else {
			return date;
		}
	}
	
	/*
	 * 将字符串转换为字符集为utf-8的字符串
	 */
	public static String chStr(String str){
		String cStr=str;
		if(str == null){
			cStr = "";
		}
		else{
			try{
				cStr = new String(str.getBytes("iso-8859-1"),"utf-8");
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		
		return cStr;
	}
	
	/*
	 * 编写显示文本中的回车、空格及保证html标记的正常输出方法
	 */
	public String convertStr(String str){
		String cvtStr = str;
		if(str == null){
			cvtStr = "";
		}else{
			try{
				cvtStr = str.replaceAll("<", "&lt;");
				cvtStr = str.replaceAll(">", "&gt;");
				cvtStr = str.replaceAll(" ", "&nbsp;");
				cvtStr = str.replaceAll("\r\n", "<br>");
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		return cvtStr;
	}
	
	/*
	 * 将一个日期格式的字符串装换为对应的Timestamp对象
	 * toTimestamp("1982-12-02 9:26:44"); 
	 * toTimestamp("1982-12-02");
	 */
	public static Timestamp toTimestamp(String date){
		try {
			if(date.length()>10 && date.indexOf(":")>0){ //用该算法识别日期字符串中是否拥有时间内容
				Format f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date d = (Date)f.parseObject(date); 
				Timestamp ts = new Timestamp(d.getTime());
				return ts;
			}
			else{
				Format f = new SimpleDateFormat("yyyy-MM-dd");
				Date d = (Date)f.parseObject(date); 
				Timestamp ts = new Timestamp(d.getTime());
				return ts;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/*
	 * 将一个日期格式的date对象装换为对应的Timestamp对象
	 */
	public static Timestamp toTimestamp(Date date){
		Timestamp ts = new Timestamp(date.getTime());
		return ts;
	}
	
	/*
	 * 获得并返回一个客户端的当前日期及时间的Timestamp对象
	 */
	public static Timestamp toTodayTimestamp(){
		Timestamp ts = new Timestamp(new Date().getTime());
		return ts;
	}
	
	
	public static void main(String args[]){
		System.out.println(toTodayTimestamp());
	}
}
